package org.microsites.domain.dao.eod;

import java.util.List;

import net.lemnik.eodsql.BaseQuery;
import net.lemnik.eodsql.DataSet;
import net.lemnik.eodsql.GeneratedKeys;
import net.lemnik.eodsql.Select;
import net.lemnik.eodsql.Update;

import org.microsites.domain.dao.GroupDAO;
import org.microsites.domain.model.Group;
import org.microsites.util.EodDaoSupport;

public class GroupDAOImpl extends EodDaoSupport implements GroupDAO {
	private Query query;
	
	@Override
	public void create(Group entity) {
		entity.setId(getQuery().create(entity));
	}

	@Override
	public void delete(Long id) {
		getQuery().delete(id);
	}

	@Override
	public List<Group> list() {
		return getQuery().list();
	}

	@Override
	public List<Group> sublist(Long id) {
		return id == null ? getQuery().rootlist() : getQuery().sublist(id);
	}

	@Override
	public Group load(Long id) {
		return getQuery().load(id);
	}

	@Override
	public void update(Group entity) {
		getQuery().update(entity);
	}
	
	public Query getQuery() {
		return query == null ? query = super.getQuery(Query.class) : query;
	}

	@Override
	public List<String> autocomplete(String column, String pattern) {
		return super.select(String.class, "SELECT " + column + " FROM [Group] WHERE " + column + " LIKE ?1 GROUP BY " + column, '%' + pattern + '%');
	}
	
	@Override
	public Group getRoot(String name) {
		return getQuery().getRoot(name);
	}

	static interface Query extends BaseQuery {

		@Select(sql = "SELECT * FROM [Group]")
		public DataSet<Group> list();
		
		@Select(sql = "SELECT * FROM [Group] WHERE parent=?1")
		public DataSet<Group> sublist(Long id);

		@Select(sql = "SELECT * FROM [Group] WHERE parent IS NULL")
		public DataSet<Group> rootlist();

		@Select(sql = "SELECT * FROM [Group] WHERE name=?1 AND parent IS NULL")
		public Group getRoot(String name);

		@Select(sql = "SELECT * FROM [Group] WHERE id=?1")
		public Group load(Long id);

        @Update(sql = "INSERT INTO [Group] (name,description,parent) VALUES (?{1.name},?{1.description},?{1.parent})",
                keys = GeneratedKeys.RETURNED_KEYS_FIRST_COLUMN)
		public Long create(Group dg);
		
        @Update(sql = "UPDATE [Group] SET name=?{1.name},description=?{1.description},parent=?{1.parent} WHERE id=?{1.id}")
		public void update(Group dg);
		
		@Update(sql = "DELETE FROM [Group] WHERE id=?1")
		public void delete(Long id);
	}

}
